﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Body : MonoBehaviour, ICanTakeDamage
{
    private Monster monster;
    private BoxCollider2D boxCollider;
    private float prevTakeDamageTime = 0.0f;

    private void Start()
    {
        monster = transform.parent.GetComponent<Monster>();
        boxCollider = GetComponent<BoxCollider2D>();
    }


    public void TakeDamage(DamageInfo damageInfo, GameObject attacker, bool breakAction)
    {
        if (!monster.animController.IsCurrAnimName(MonsterAnimName.Fall))
        {
            if (monster.seriesTakeDamageCount == 0 || Time.time - prevTakeDamageTime <= 1.0f)
            {
                ++monster.seriesTakeDamageCount;
                prevTakeDamageTime = Time.time;
            }
            else
            {
                monster.seriesTakeDamageCount = 0;
            }

            //受伤乃优先级最高，无论任何状态下，只要受伤，都应该马上进行处理
            MonsterTaskProcessor.Instance.AddTaskFront(new MonsterTaskHit(monster, null, 1.5f, damageInfo, attacker, breakAction));
            monster.GetComponent<SpriteRenderer>().color = Color.red;
            Invoke("ResetColor", 0.25f);
        }
    }

    private void ResetColor()
    {
        monster.GetComponent<SpriteRenderer>().color = Color.white;
    }



    /// <summary>
    /// 地面和天花板碰撞检测
    /// </summary>
    private void OnTriggerEnter2D(Collider2D collision)
    {
        OnTriggerStay2D(collision);
    }


    private void OnTriggerStay2D(Collider2D collision)
    {
        //TODO 对于障碍物的碰撞检测
        if (collision.gameObject.tag == GameObjectTags.groundTag)
        {
            if (!monster.IsGround)
            {
                float y = boxCollider.bounds.max.y - collision.bounds.max.y - boxCollider.bounds.size.y;
                if (y <= 0 && -y > collision.bounds.min.y)
                {
                    monster.IsGround = true;
                    monster.transform.position = new Vector3(monster.transform.position.x, collision.bounds.max.y + boxCollider.bounds.extents.y, monster.transform.position.z);
                }
            }

            if (!monster.IsCeiling)
            {
                float y = collision.bounds.min.y - boxCollider.bounds.min.y - boxCollider.bounds.size.y;
                //if (y >= collision.bounds.min.y)
                //{
                //    monster.IsCeiling = true;

                //    //调整位置，以免身体部分陷入天花板中
                //     monster.transform.position = new Vector3(monster.transform.position.x, collision.bounds.min.y - boxCollider.bounds.extents.y, monster.transform.position.z);
                //}
            }
        }
    }


    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == GameObjectTags.groundTag)
        {
            monster.IsGround = false;
            monster.IsCeiling = false;
        }
    }
}
